{% extends 'base.html' %}

{% block content %}

<!-- Global Search & Replace Panel (floating on the left side) -->
<div id="search-replace-panel" class="search-replace-panel">
    <div class="search-replace-toggle">
        <a id="search-replace-toggle-btn" class="search-replace-toggle-btn tooltipped" data-position="bottom" data-tooltip="Global Search & Replace">
            <i class="material-icons">find_replace</i>
        </a>
    </div>
    <div id="search-replace-content" class="search-replace-content hide">
        <div class="search-replace-header">
            <h5>{{ _('Global Search & Replace') }}</h5>
            <a class="search-replace-close"><i class="material-icons">close</i></a>
        </div>
        <div class="search-replace-form">
            <div class="input-field">
                <input id="search-text" type="text" placeholder="{{ _('Text to search') }}">
                <label for="search-text" class="active">{{ _('Search') }}</label>
            </div>
            <div class="input-field">
                <input id="replace-text" type="text" placeholder="{{ _('Replace with') }}">
                <label for="replace-text" class="active">{{ _('Replace') }}</label>
            </div>
            <div class="search-replace-buttons">
                <button id="search-btn" class="btn waves-effect waves-light blue">
                    <i class="material-icons left">search</i>{{ _('Search') }}
                </button>
                <button id="replace-btn" class="btn waves-effect waves-light green" disabled>
                    <i class="material-icons left">find_replace</i>Replace
                </button>
            </div>
        </div>
        <div class="search-results-container">
            <h6>{{ _('Search Results') }} <span id="search-count" class="badge">0</span></h6>
            <div id="search-results" class="search-results">
                <!-- Search results will be added dynamically via JavaScript -->
                <div class="no-results center-align">
                    <p>{{ _('No results') }}</p>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Task Statistics Chart (floating on the left side) -->
<div id="statistics-section" class="chart-float">
    <canvas id="tasks-chart"></canvas>
</div>

<!-- Notification Icon (top right corner) -->
<div id="notification-icon" class="notification-container">
    <a class="notification-bell tooltipped" data-position="bottom" data-tooltip="{{ _('Task Reminders') }}">
        <i class="material-icons">notifications</i>
        <span id="notification-count" class="notification-badge hide">0</span>
    </a>
    <!-- Notification Popup -->
    <div id="notification-popup" class="notification-popup hide">
        <div class="notification-header">
            <h5>{{ _('Upcoming Tasks') }}</h5>
            <a class="notification-close"><i class="material-icons">close</i></a>
        </div>
        <div class="notification-content">
            <div id="upcoming-tasks-list">
                <!-- Task list will be added dynamically via JavaScript -->
            </div>
            <div id="no-upcoming-tasks" class="center-align">
                <p>{{ _('No upcoming tasks') }}</p>
            </div>
        </div>
    </div>
</div>

<!-- Backup & Restore Function -->
<div id="backup-panel" class="backup-panel">
    <div class="backup-icon">
        <a id="backup-toggle" class="backup-toggle tooltipped" data-position="bottom" data-tooltip="{{ _('Backup & Restore') }}">
            <i class="material-icons">save</i>
        </a>
    </div>
    <div id="backup-content" class="backup-content hide">
        <div class="backup-header">
            <h5>{{ _('Backup & Restore') }}</h5>
            <a class="backup-close"><i class="material-icons">close</i></a>
        </div>
        <div class="backup-actions">
            <button id="create-backup-btn" class="btn waves-effect waves-light green">
                <i class="material-icons left">add</i>{{ _('Create Backup') }}
            </button>
        </div>
        <div class="backup-list-container">
            <h6>{{ _('Backup List') }} <small>(Max 10)</small></h6>
            <div id="backups-list" class="backups-list">
                <!-- Backup list will be added dynamically via JavaScript -->
                <div class="no-backups center-align">
                    <p>{{ _('No backups') }}</p>
                </div>
            </div>
        </div>
    </div>
</div>

<header class="row compact-header">
    <div class="input-field col s12 m6">
        <input id="item-input" data-href="{{ url_for('.new_item') }}"
               type="text" placeholder="{{ _('What needs to be done?') }}" autocomplete="off" autofocus required>
    </div>
    <div class="input-field col s6 m2">
        <select id="category-select">
            <option value="Work">{{ _('Work') }}</option>
            <option value="Life">{{ _('Life') }}</option>
            <option value="Study">{{ _('Study') }}</option>
            <option value="Game">{{ _('Game') }}</option>
            <option value="Other" selected>{{ _('Other') }}</option>
        </select>
        
    </div>
    <div class="input-field col s6 m2">
        <div class="date-icon-wrapper">
            <input id="due-time" type="text" class="date-input-hidden" data-href="{{ url_for('.new_item') }}" 
                   onfocus="this.type='datetime-local'" 
                   onblur="if(this.value==='')this.type='text'">
            <div id="date-icon-overlay" class="date-square-icon tooltipped" data-position="bottom" data-tooltip="{{ _('Select Date') }}">
                <i class="material-icons">event</i>
            </div>
        </div>
    </div>
    <div class="input-field col s12 m2">
        <button id="submit-btn" class="btn waves-effect waves-light" type="submit">{{ _('Add') }}</button>
    </div>
</header>
<style>
    /* 更紧凑的头部样式 */
    .compact-header {
        display: flex;
        align-items: center;
        margin-bottom: 15px;
        gap: 8px;
    }
    .compact-header .input-field {
        margin-top: 0;
        margin-bottom: 0;
        padding-left: 4px;
        padding-right: 4px;
    }
    #submit-btn {
        width: 100%;
        height: 36px;
        line-height: 36px;
        padding: 0 10px;
    }
    /* Unified styles for time selection and task input */
    #due-time {
        height: 3rem;
        font-size: 16px;
        border: 1px solid #9e9e9e;
        border-radius: 2px;
        padding: 0 8px;
        box-sizing: border-box;
        background-color: transparent;
    }
    #due-time:focus {
        border-bottom: 1px solid #26a69a;
        box-shadow: 0 1px 0 0 #26a69a;
    }
    /* Hide the default date label for time input */
    .date-label {
        font-size: 14px;
        transform: translateY(-14px);
    }
    /* Date icon styling */
    .date-icon-wrapper {
        position: relative;
        display: flex;
        align-items: center;
        height: 3rem; /* 与Materialize select高度一致 */
        width: 100%;
    }
    
    #due-time {
        width: 36px;
        height: 36px;
        opacity: 1;
        cursor: pointer;
        z-index: 2;
        background-color: transparent;
        position: absolute;
        right: 0;
        top: 50%;
        transform: translateY(-50%);
        padding: 0;
        margin: 0;
        border: none;
    }
    
    .date-input-hidden {
        box-shadow: none !important;
    }
    
    #date-icon-overlay {
        position: absolute;
        right: 0;
        top: 50%;
        transform: translateY(-50%);
        display: flex;
        align-items: center;
        justify-content: center;
        background-color: #26a69a;
        width: 36px;
        height: 36px;
        border-radius: 3px;
        transition: background-color 0.3s;
        z-index: 3;
        pointer-events: none; /* Allow clicks to pass through to the input */
    }
    
    #due-time:hover + #date-icon-overlay {
        background-color: #2bbbad;
    }
    
    #date-icon-overlay i {
        line-height: normal;
    }
    
    .input-field .btn-floating {
        margin-top: 5px;
    }
    /* Chart floating styles */
    .chart-float {
        position: fixed;
        left: 10px;
        top: 50%;
        transform: translateY(-50%);
        width: 180px;
        z-index: 100;
        transition: all 0.3s ease;
        background-color: transparent;
    }
    @media (max-width: 992px) {
        .chart-float {
            position: static;
            width: 100%;
            transform: none;
            margin-bottom: 20px;
        }
    }
    
    /* Notification icon styles */
    .notification-container {
        position: fixed;
        top: 15px;
        right: 15px;
        z-index: 1000;
    }
    
    .notification-bell {
        position: relative;
        display: inline-block;
        width: 40px;
        height: 40px;
        border-radius: 50%;
        background-color: #ff5252;
        text-align: center;
        line-height: 40px;
        cursor: pointer;
        box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
    }
    
    .notification-bell i {
        color: white;
        line-height: 40px;
    }
    
    .notification-badge {
        position: absolute;
        top: -5px;
        right: -5px;
        background-color: #F44336;
        color: white;
        border-radius: 50%;
        width: 20px;
        height: 20px;
        font-size: 12px;
        text-align: center;
        line-height: 20px;
        font-weight: bold;
        box-shadow: 0 2px 2px rgba(0, 0, 0, 0.2);
    }
    
    .notification-popup {
        position: absolute;
        top: 50px;
        right: 0;
        width: 300px;
        max-height: 400px;
        background-color: white;
        border-radius: 4px;
        box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
        overflow: hidden;
    }
    
    .notification-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 10px 15px;
        background-color: #f5f5f5;
        border-bottom: 1px solid #e0e0e0;
    }
    
    .notification-header h5 {
        margin: 0;
        font-size: 16px;
        font-weight: 500;
    }
    
    .notification-close {
        cursor: pointer;
    }
    
    .notification-content {
        max-height: 350px;
        overflow-y: auto;
        padding: 10px;
    }
    
    .upcoming-task-item {
        padding: 10px;
        border-bottom: 1px solid #e0e0e0;
        display: flex;
        flex-direction: column;
    }
    
    .upcoming-task-title {
        font-weight: 500;
        margin-bottom: 5px;
    }
    
    .upcoming-task-info {
        display: flex;
        justify-content: space-between;
        font-size: 12px;
        color: #757575;
    }
    
    .upcoming-task-time {
        color: #F44336;
        font-weight: bold;
    }
    
    .upcoming-task-category {
        padding: 2px 5px;
        border-radius: 3px;
        color: white;
        display: inline-block;
        font-size: 11px;
    }
    
    /* Backup functionality styles */
    .backup-panel {
        position: fixed;
        top: 65px;
        right: 15px;
        z-index: 999;
    }
    
    .backup-toggle {
        position: relative;
        display: inline-block;
        width: 40px;
        height: 40px;
        border-radius: 50%;
        background-color: #4CAF50;
        text-align: center;
        line-height: 40px;
        cursor: pointer;
        box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
    }
    
    .backup-toggle i {
        color: white;
        line-height: 40px;
    }
    
    .backup-content {
        position: absolute;
        top: 50px;
        right: 0;
        width: 300px;
        max-height: 400px;
        background-color: white;
        border-radius: 4px;
        box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
        overflow: hidden;
    }
    
    .backup-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 10px 15px;
        background-color: #f5f5f5;
        border-bottom: 1px solid #e0e0e0;
    }
    
    .backup-header h5 {
        margin: 0;
        font-size: 16px;
        font-weight: 500;
    }
    
    .backup-close {
        cursor: pointer;
    }
    
    .backup-actions {
        padding: 10px 15px;
        text-align: center;
        border-bottom: 1px solid #e0e0e0;
    }
    
    .backup-list-container {
        padding: 10px 15px;
    }
    
    .backup-list-container h6 {
        margin-top: 0;
        margin-bottom: 10px;
        font-size: 14px;
        font-weight: 500;
    }
    
    .backups-list {
        max-height: 250px;
        overflow-y: auto;
    }
    
    .backup-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 8px 10px;
        border-bottom: 1px solid #e0e0e0;
        font-size: 13px;
    }
    
    .backup-time {
        flex: 1;
    }
    
    .backup-actions-buttons a {
        margin-left: 5px;
        cursor: pointer;
        color: #039be5;
    }
    
    .backup-actions-buttons a:hover {
        color: #0277bd;
    }
    
.no-backups {
        padding: 20px 0;
        color: #757575;
    }
    
    /* Search & Replace panel styles */
    .search-replace-panel {
        position: fixed;
        top: 115px; /* 放置在通知和备份按钮下方 */
        right: 15px; /* 与通知和备份按钮右对齐 */
        z-index: 999;
    }
    
    .search-replace-toggle-btn {
        position: relative;
        display: inline-block;
        width: 40px;
        height: 40px;
        border-radius: 50%;
        background-color: #039be5;
        text-align: center;
        line-height: 40px;
        cursor: pointer;
        box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
    }
    
    .search-replace-toggle-btn i {
        color: white;
        line-height: 40px;
    }
    
    .search-replace-content {
        position: absolute;
        top: 50px;
        right: 0; /* 右侧对齐 */
        width: 300px;
        max-height: 400px;
        background-color: white;
        border-radius: 4px;
        box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
        overflow: hidden;
    }
    
    .search-replace-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 10px 15px;
        background-color: #f5f5f5;
        border-bottom: 1px solid #e0e0e0;
    }
    
    .search-replace-header h5 {
        margin: 0;
        font-size: 16px;
        font-weight: 500;
    }
    
    .search-replace-close {
        cursor: pointer;
    }
    
    .search-replace-form {
        padding: 15px;
        border-bottom: 1px solid #e0e0e0;
    }
    
    .search-replace-form .input-field {
        margin-top: 8px;
        margin-bottom: 8px;
    }
    
    .search-replace-buttons {
        display: flex;
        justify-content: space-between;
        margin-top: 15px;
    }
    
    .search-results-container {
        padding: 10px 15px;
    }
    
    .search-results-container h6 {
        margin-top: 0;
        margin-bottom: 10px;
        font-size: 14px;
        font-weight: 500;
    }
    
    .search-results {
        max-height: 150px;
        overflow-y: auto;
    }
    
    .search-result-item {
        padding: 8px 10px;
        border-bottom: 1px solid #e0e0e0;
        font-size: 13px;
        cursor: pointer;
    }
    
    .search-result-item:hover {
        background-color: #f5f5f5;
    }
    
    .search-result-text {
        margin-bottom: 4px;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
    }
    
    .search-result-category {
        display: inline-block;
        font-size: 11px;
        padding: 2px 5px;
        border-radius: 3px;
        color: white;
        margin-right: 5px;
    }
    
    .search-result-match {
        background-color: #ffeb3b;
        padding: 1px 2px;
        border-radius: 2px;
    }
    
    .no-results {
        padding: 20px 0;
        color: #757575;
    }
</style>
    <div class="row" id="dashboard">
        <div class="col l9 m12 s12">
            <ul class="tabs">
                <li class="tab col m3 s12">
                    <a class="blue-text button" id="all-item">
                        {{ _('All') }} <span class="grey-text small-text" id="all-count">{{ all_count }}</span>
                    </a>
                </li>
                <li class="tab col m3 s12">
                    <a class="blue-text button" id="active-item">
                        {{ _('Active') }} <span class="grey-text small-text" id="active-count">{{ active_count }}</span>
                    </a>
                </li>
                <li class="tab col m3 s12">
                    <a class="blue-text button" id="completed-item">
                        {{ _('Done') }} <span class="grey-text small-text"
                                              id="completed-count">{{ completed_count }}</span>
                    </a>
                </li>
                <li class="tab col m3 s12">
                    <a class="red-text button" id="overdue-item">
                        {{ _('Overdue') }} <span class="grey-text small-text"
                                              id="overdue-count">0</span>
                    </a>
                </li>
            </ul>
        </div>
        <div class="col l3 hide-on-med-and-down">
            <a class="waves-effect waves-light btn red right" id="clear-btn">
                <i class="material-icons left">clear_all</i>{{ _('Clear') }}
            </a>
        </div>
    </div>
    
    <!-- Category filter buttons -->
    <div class="row" id="category-filters">
        <div class="col s12 center-align">
            <span class="category-filter all active" data-category="all">{{ _('All') }}</span>
            <span class="category-filter Work" data-category="Work">{{ _('Work') }}</span>
            <span class="category-filter Life" data-category="Life">{{ _('Life') }}</span>
            <span class="category-filter Study" data-category="Study">{{ _('Study') }}</span>
            <span class="category-filter Game" data-category="Game">{{ _('Game') }}</span>
            <span class="category-filter Other" data-category="Other">{{ _('Other') }}</span>
        </div>
    </div>

<div class="items">
    {% for item in items %}
        {% include '_item.html' %}
    {% endfor %}
</div>
<script src="{{ url_for('static', filename='js/datetime-input.js') }}"></script>
<script>
$(document).ready(function() {
    // Initialize Materialize select
    $('select').formSelect();
    
    // Initialize Materialize tabs
    $('ul.tabs').tabs();
    
    // Task statistics chart variables
    let tasksChart = null;
    
    // Define category colors
    const categoryColors = {
        'Work': '#f44336', // Red
        'Life': '#4CAF50', // Green
        'Study': '#2196F3', // Blue
        'Game': '#FF9800', // Orange
        'Other': '#9E9E9E'  // Gray
    };
    
    // Initialize Materialize components
    function activeM() {
        $('.sidenav').sidenav();
        $('ul.tabs').tabs();
        $('.modal').modal();
        $('.tooltipped').tooltip();
        $('.dropdown-trigger').dropdown({
            constrainWidth: false,
            coverTrigger: false
        });
        display_dashboard();
        
        // Ensure default filter option is set on first load
        if ($('.tab.active').length === 0) {
            $('#all-item').parent().addClass('active');
        }
    }

    // Show/hide dashboard
    function display_dashboard() {
        var all_count = $('.item').length;
        if (all_count === 0) {
            $('#dashboard').hide();
        } else {
            $('#dashboard').show();
            $('ul.tabs').tabs();
        }
    }
    
    // Load and display statistics chart
    function loadStatistics() {
        $.ajax({
            url: '{{ url_for('.get_statistics') }}',
            type: 'GET',
            success: function(data) {
                drawChart(data);
            },
            error: function(xhr) {
                console.error('Error loading statistics:', xhr);
                M.toast({html: 'Failed to load statistics'});
            }
        });
    }
    
    // Add CSS style to fix chart height
    $('head').append(`
        <style>
            #tasks-chart {
                width: 100%;
                height: 180px;
                background-color: transparent;
            }
        </style>
    `);

    // Draw statistics chart
    function drawChart(data) {
        // Calculate completed and active task totals
        const completedTotal = data.completed.reduce((sum, current) => sum + current, 0);
        const activeTotal = data.active.reduce((sum, current) => sum + current, 0);
        const totalTasks = completedTotal + activeTotal;
        
        // Calculate completion rate percentage
        const completionRate = totalTasks === 0 ? 0 : Math.round((completedTotal / totalTasks) * 100);
        
        // Define category colors
        const colors = {
            'Work': '#F44336', // Red
            'Life': '#2196F3', // Blue
            'Study': '#4CAF50', // Green
            'Game': '#FF9800', // Orange
            'Other': '#9E9E9E'  // Gray
        };
        
        // Create complete dataset
        let chartLabels = [];
        let chartData = [];
        let chartColors = [];
        let chartBackgroundColors = [];
        
        // Create two data points for each category (completed and active)
        data.categories.forEach((category, index) => {
            // Active tasks
            if(data.active[index] > 0) {
                chartLabels.push(`${category}(Active)`);
                chartData.push(data.active[index]);
                // Use category color with reduced opacity
                chartColors.push(colors[category] || '#9E9E9E');
                chartBackgroundColors.push(`${colors[category]}99` || '#9E9E9E99');
            }
            
            // Completed tasks
            if(data.completed[index] > 0) {
                chartLabels.push(`${category}(Completed)`);
                chartData.push(data.completed[index]);
                // Use dark version of category color
                chartColors.push(colors[category] || '#9E9E9E');
                chartBackgroundColors.push(`${colors[category]}` || '#9E9E9E');
            }
        });
        
        // Create pie chart data
        const pieData = {
            labels: chartLabels,
            datasets: [{
                data: chartData,
                backgroundColor: chartBackgroundColors,
                borderColor: chartColors,
                borderWidth: 1
            }]
        };
        
        // Chart configuration options
        const chartOptions = {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'bottom',
                    labels: {
                        boxWidth: 10,
                        font: {
                            size: 9
                        },
                        padding: 5
                    }
                },
                tooltip: {
                    callbacks: {
                        label: function(context) {
                            const label = context.label || '';
                            const value = context.formattedValue || '';
                            const percentage = Math.round(context.raw / totalTasks * 100);
                            return `${label}: ${value} (${percentage}%)`;
                        }
                    }
                },
                title: {
                    display: true,
                    text: '{{ _('Task Category Statistics') }}',
                    font: {
                        size: 12
                    },
                    padding: {
                        bottom: 10
                    }
                }
            }
        };
        
        // Destroy old chart if exists
        if (tasksChart) {
            tasksChart.destroy();
        }
        
        // Create pie chart
        const ctx = document.getElementById('tasks-chart').getContext('2d');
        tasksChart = new Chart(ctx, {
            type: 'pie',
            data: pieData,
            options: chartOptions
        });
        
        // Show or hide chart section based on data
        const hasData = totalTasks > 0;
        
        if (!hasData) {
            $('#statistics-section').hide();
        } else {
            $('#statistics-section').show();
        }
    }
    
    // Initial statistics chart load
    loadStatistics();
    
    // Show selected date indicator and clear button when date is selected
    $('#due-time').on('change', function() {
        if($(this).val()) {
            // Add visual indicator that date is selected
            $('#date-icon-overlay').addClass('active').css('background-color', '#f44336');
            
            // If clear button doesn't exist yet, add it
            if($('#clear-date').length === 0) {
                const $clearBtn = $('<a id="clear-date" class="btn-floating btn-small red" style="position:absolute; right:-10px; top:-10px; width:20px; height:20px; display:flex; align-items:center; justify-content:center; z-index:3;"><i class="material-icons" style="font-size:14px; line-height:normal;">close</i></a>');
                $('.date-icon-wrapper').css('position', 'relative').append($clearBtn);
                
                // Add click handler for clear button
                $clearBtn.on('click', function(e) {
                    e.stopPropagation(); // Prevent triggering date picker
                    $('#due-time').val(''); // Clear date value
                    $('#date-icon-overlay').removeClass('active').css('background-color', '#26a69a');
                    $(this).remove(); // Remove clear button
                });
            }
        } else {
            // Reset to default state if date is cleared
            $('#date-icon-overlay').removeClass('active').css('background-color', '#26a69a');
            $('#clear-date').remove();
        }
    });
    
    // Define global function for datetime-input.js reference
    window.submitItem = function() {
        const body = $('#item-input').val().trim();
        if (!body) return;
        
        const deadlineInput = $('#due-time').val();
        // Handle timezone issues correctly, preserving local time
        let deadline = null;
        if (deadlineInput) {
            // Create a date object but keep local time unchanged
            const localDate = new Date(deadlineInput);
            
            // Calculate local time and UTC time offset (minutes)
            const timezoneOffset = localDate.getTimezoneOffset();
            
            // Create a new date, add offset to compensate for browser auto-conversion
            const adjustedDate = new Date(localDate.getTime() - (timezoneOffset * 60000));
            
            // Use ISO format but remove Z suffix (UTC indicator), so backend knows it's local time
            deadline = adjustedDate.toISOString().slice(0, -1);
        }
        // Get selected category
        const category = $('#category-select').val();
        
        $.ajax({
            url: $('#item-input').data('href'),
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify({
                body: body, 
                deadline: deadline,
                category: category,
                order: 0  // Add default order value
            })
        })
        .done(function(data) {
            $('.items').prepend(data.html);
            $('#item-input').val(''); // Clear input field
            // Refresh statistics chart
            loadStatistics();
            // Reinitialize UI components
            activeM();
            // Refresh counters
            refresh_count();
            // Reapply filters
            applyAllFilters();
        })
        .fail(function(xhr) {
            console.error('Error:', xhr);
            alert('{{ _('Failed to create item.') }}');
        });
    }
    
    // Enter key submission
    $('#item-input').on('keypress', function(e) {
        if (e.which === 13) {
            submitItem();
        }
    });
    
    // Add button click submission
    $('#submit-btn').on('click', function() {
        submitItem();
    });
    
    // Apply all current filters (category and completion status)
    function applyAllFilters() {
        var selectedCategory = $('.category-filter.active').data('category');
        var filterType = '';
        
        if ($('#completed-item').parent().hasClass('active')) {
            filterType = 'completed';
        } else if ($('#active-item').parent().hasClass('active')) {
            filterType = 'active';
        } else if ($('#overdue-item').parent().hasClass('active')) {
            filterType = 'overdue';
        }
        
        // First show all tasks
        $('.item').show();
        
        // Apply category filter
        if (selectedCategory && selectedCategory !== 'all') {
            $('.item').filter(function() {
                return $(this).data('category') !== selectedCategory;
            }).hide();
        }
        
        // Apply task status filter
        if (filterType === 'completed') {
            $('.item:visible').filter(function() {
                return !$(this).data('done');
            }).hide();
        } else if (filterType === 'active') {
            $('.item:visible').filter(function() {
                return $(this).data('done');
            }).hide();
        } else if (filterType === 'overdue') {
            $('.item:visible').filter(function() {
                // Only show incomplete tasks that are past due
                var now = new Date();
                
                // If task is complete, hide it
                if ($(this).data('done') === true) {
                    return true;
                }
                
                // If no deadline, hide it
                if (!$(this).find('.deadline-text').length) {
                    return true;
                }
                
                // Get deadline time
                var deadlineText = $(this).find('.deadline-text').text().trim();
                var deadlineDate = new Date(deadlineText);
                
                // If deadline is later than current time (not overdue), hide it
                return deadlineDate > now;
            }).hide();
        }
    }
    
    // Category filter functionality
    $('.category-filter').on('click', function() {
        // Update active state
        $('.category-filter').removeClass('active');
        $(this).addClass('active');
        
        // Apply all filters
        applyAllFilters();
    });
    
    // All/Active/Completed task filtering
    $(document).on('click', '#all-item', function() {
        $('#item-input').focus();
        // Ensure tab is correctly activated
        $(this).parent().addClass('active').siblings().removeClass('active');
        applyAllFilters();
    });
    
    $(document).on('click', '#active-item', function() {
        $('#item-input').focus();
        // Ensure tab is correctly activated
        $(this).parent().addClass('active').siblings().removeClass('active');
        applyAllFilters();
    });
    
    $(document).on('click', '#completed-item', function() {
        $('#item-input').focus();
        // Ensure tab is correctly activated
        $(this).parent().addClass('active').siblings().removeClass('active');
        applyAllFilters();
    });
    
    $(document).on('click', '#overdue-item', function() {
        $('#item-input').focus();
        // Ensure tab is correctly activated
        $(this).parent().addClass('active').siblings().removeClass('active');
        applyAllFilters();
    });
    
    // Refresh task counts
    function refresh_count() {
        var $items = $('.item');
        var now = new Date();

        // Show/hide dashboard
        if ($items.length === 0) {
            $('#dashboard').hide();
        } else {
            $('#dashboard').show();
            $('ul.tabs').tabs();
        }
        
        var all_count = $items.length;
        var active_count = $items.filter(function () {
            return $(this).data('done') === false;
        }).length;
        var completed_count = $items.filter(function () {
            return $(this).data('done') === true;
        }).length;
        
        // Calculate overdue task count
        var overdue_count = $items.filter(function() {
            // Only consider incomplete tasks with deadlines
            if ($(this).data('done') === true || !$(this).find('.deadline-text').length) {
                return false;
            }
            
            // Get deadline text and convert to Date object
            var deadlineText = $(this).find('.deadline-text').text().trim();
            var deadlineDate = new Date(deadlineText);
            
            // If deadline is earlier than current time, it's overdue
            return deadlineDate < now;
        }).length;
        
        $('#all-count').html(all_count);
        $('#active-count').html(active_count);
        $('#active-count-nav').html(active_count);
        $('#completed-count').html(completed_count);
        $('#overdue-count').html(overdue_count);
        
        // If there are overdue tasks, add pulsing effect to the label
        if (overdue_count > 0) {
            $('#overdue-item').addClass('pulse-text');
        } else {
            $('#overdue-item').removeClass('pulse-text');
        }
    }
    
    // Mark task as complete/incomplete
    $(document).on('click', '.done-btn', function () {
        var $input = $('#item-input');

        $input.focus();
        var $item = $(this).parent().parent();
        var $this = $(this);

        if ($item.data('done')) {
            $.ajax({
                type: 'PATCH',
                url: $this.data('href'),
                success: function (data) {
                    $this.next().removeClass('inactive-item');
                    $this.next().addClass('active-item');
                    $this.find('i').text('check_box_outline_blank');
                    $item.data('done', false);
                    M.toast({html: data.message});
                    refresh_count();
                    // Refresh statistics chart
                    loadStatistics();
                    // Reapply filters
                    applyAllFilters();
                }
            })
        } else {
            $.ajax({
                type: 'PATCH',
                url: $this.data('href'),
                success: function (data) {
                    $this.next().removeClass('active-item');
                    $this.next().addClass('inactive-item');
                    $this.find('i').text('check_box');
                    $item.data('done', true);
                    M.toast({html: data.message});
                    refresh_count();
                    // Refresh statistics chart
                    loadStatistics();
                    // Reapply filters
                    applyAllFilters();
                }
            })
        }
    });

    // Delete task
    $(document).on('click', '.delete-btn', function () {
        var $input = $('#item-input');
        var $item = $(this).parent().parent();

        $input.focus();
        $.ajax({
            type: 'DELETE',
            url: $(this).data('href'),
            success: function (data) {
                $item.remove();
                // Initialize UI components
                activeM();
                refresh_count();
                // Refresh statistics chart
                loadStatistics();
                // Reapply filters
                applyAllFilters();
                M.toast({html: data.message});
            }
        });
    });
    
    // Clear button functionality - clear all tasks
    $(document).on('click', '#clear-btn', function () {
        if (!confirm('{{ _("Are you sure you want to delete ALL tasks?") }}')) {
            return;  // User cancelled operation
        }
        
        var $input = $('#item-input');
        var $items = $('.item');

        $input.focus();
        $.ajax({
            type: 'DELETE',
            url: clear_item_url,
            success: function (data) {
                // Delete all tasks
                $items.remove();
                M.toast({html: data.message, classes: 'rounded'});
                refresh_count();
                // Initialize UI components
                activeM();
                // Refresh statistics chart
                loadStatistics();
                // Reset filters (after clearing all tasks)
                $('.category-filter').removeClass('active');
                $('.category-filter.all').addClass('active');
            }
        });
    });
    
    // Initialize UI components
    activeM();
    
    // ==== Task Reminder Functionality ==== //
    
    // Get upcoming tasks
    function loadUpcomingTasks() {
        $.ajax({
            url: '{{ url_for('.get_upcoming_tasks') }}',
            type: 'GET',
            success: function(data) {
                updateNotificationBadge(data.count);
                renderUpcomingTasks(data.tasks);
            },
            error: function(xhr) {
                console.error('Error loading upcoming tasks:', xhr);
            }
        });
    }
    
    // Update notification badge
    function updateNotificationBadge(count) {
        const $badge = $('#notification-count');
        if (count > 0) {
            $badge.text(count).removeClass('hide');
            // Add pulsing animation class
            $('.notification-bell').addClass('pulse');
        } else {
            $badge.addClass('hide');
            $('.notification-bell').removeClass('pulse');
        }
    }
    
    // Render upcoming tasks list
    function renderUpcomingTasks(tasks) {
        const $tasksList = $('#upcoming-tasks-list');
        const $noTasks = $('#no-upcoming-tasks');
        
        $tasksList.empty();
        
        if (tasks.length === 0) {
            $noTasks.show();
            return;
        }
        
        $noTasks.hide();
        
        tasks.forEach(task => {
            const remainingText = task.remaining_minutes <= 60 
                ? `${task.remaining_minutes} min` 
                : `${Math.floor(task.remaining_minutes / 60)}h ${task.remaining_minutes % 60}m`;
            
            const taskHtml = `
                <div class="upcoming-task-item" data-id="${task.id}">
                    <div class="upcoming-task-title">${task.body}</div>
                    <div class="upcoming-task-info">
                        <span class="upcoming-task-category" style="background-color: ${categoryColors[task.category] || '#9E9E9E'}">
                            ${task.category}
                        </span>
                        <span class="upcoming-task-time">{{ _('Remaining:') }} ${remainingText}</span>
                    </div>
                    <div class="upcoming-task-deadline">{{ _('Due:') }} ${task.deadline}</div>
                </div>
            `;
            
            $tasksList.append(taskHtml);
        });
        
        // Add click event for task items to scroll to the task position
        $('.upcoming-task-item').on('click', function() {
            const taskId = $(this).data('id');
            const $task = $(`.item[data-id="${taskId}"]`);
            
            if ($task.length) {
                // Ensure task is visible (might be hidden by filters)
                $('#all-item').parent().addClass('active').siblings().removeClass('active');
                $('.category-filter.all').addClass('active').siblings().removeClass('active');
                applyAllFilters();
                
                // Scroll to task position and highlight
                $('html, body').animate({
                    scrollTop: $task.offset().top - 100
                }, 500);
                
                $task.addClass('highlight-task');
                setTimeout(() => {
                    $task.removeClass('highlight-task');
                }, 2000);
                
                // Close notification popup
                $('#notification-popup').addClass('hide');
            }
        });
    }
    
    // Notification bell click event
    $('.notification-bell').on('click', function(e) {
        e.stopPropagation();
        $('#notification-popup').toggleClass('hide');
        
        // If popup is shown, update task data
        if (!$('#notification-popup').hasClass('hide')) {
            loadUpcomingTasks();
        }
    });
    
    // Close button click event
    $('.notification-close').on('click', function(e) {
        e.stopPropagation();
        $('#notification-popup').addClass('hide');
    });
    
    // Click outside to close popup
    $(document).on('click', function(e) {
        if (!$(e.target).closest('.notification-container').length) {
            $('#notification-popup').addClass('hide');
        }
    });
    
    // Prevent click events from bubbling inside popup
    $('#notification-popup').on('click', function(e) {
        e.stopPropagation();
    });
    
            // Add highlight style
    $('head').append(`
        <style>
            .highlight-task {
                animation: highlight-pulse 0.5s ease-in-out 3;
            }
            
            @keyframes highlight-pulse {
                0% { background-color: transparent; }
                50% { background-color: rgba(255, 193, 7, 0.3); }
                100% { background-color: transparent; }
            }
            
            /* Notification bell pulse animation effect */
            .notification-bell.pulse {
                animation: bell-pulse 2s infinite;
            }
            
            @keyframes bell-pulse {
                0% { transform: scale(1); }
                50% { transform: scale(1.1); }
                100% { transform: scale(1); }
            }
            
            /* Overdue task text pulse effect */
            .pulse-text {
                animation: text-pulse 2s infinite;
                font-weight: bold;
            }
            
            @keyframes text-pulse {
                0% { color: #F44336; }
                50% { color: #ff7b73; }
                100% { color: #F44336; }
            }
            
            /* 修复地址栏地址显示错误 */
            .search-replace-panel {
                box-sizing: border-box;
            }
            #search-replace-content {
                z-index: 1001;
            }
        </style>
    `);
    
    // Ensure clear_item_url is correctly defined
    var clear_item_url = "{{ url_for('.clear_items') }}";
    
    // Initial load of task reminders
    loadUpcomingTasks();
    
    // Set auto-refresh every minute
    setInterval(loadUpcomingTasks, 60000);
    
    // Refresh notifications after adding, completing or deleting tasks
    const originalSubmitItem = window.submitItem;
    window.submitItem = function() {
        originalSubmitItem.apply(this, arguments);
        // Give server time to process request
        setTimeout(loadUpcomingTasks, 500);
    };
    
    // Modify original ajax success callback
    $(document).ajaxSuccess(function(event, xhr, settings) {
        // For task add, delete or status change operations, refresh reminders
        if (settings.url.includes('/toggle') || 
            settings.url.includes('/delete') || 
            settings.url.includes('/clear') ||
            settings.url.includes('/new')) {
            // Give server time to process request
            setTimeout(loadUpcomingTasks, 500);
        }
    });
    
    // ==== Backup & Restore Functionality ==== //
    
    // Load backup list
    function loadBackups() {
        $.ajax({
            url: '{{ url_for('.get_backups') }}',
            type: 'GET',
            success: function(data) {
                renderBackupsList(data.backups);
            },
            error: function(xhr) {
                console.error('Error loading backups:', xhr);
                M.toast({html: 'Failed to load backup list'});
            }
        });
    }
    
    // Render backup list
    function renderBackupsList(backups) {
        const $backupsList = $('#backups-list');
        
        // Clear existing list
        $backupsList.empty();
        
        if (backups.length === 0) {
            $backupsList.html('<div class="no-backups center-align"><p>No backups</p></div>');
            return;
        }
        
        // Add each backup item
        backups.forEach(backup => {
            const backupHtml = `
                <div class="backup-item" data-id="${backup.id}">
                    <div class="backup-time">${backup.created_time}</div>
                    <div class="backup-actions-buttons">
                        <a class="restore-backup-btn" data-id="${backup.id}" title="Restore to this backup">
                            <i class="material-icons tiny">restore</i>
                        </a>
                        <a class="delete-backup-btn" data-id="${backup.id}" title="Delete this backup">
                            <i class="material-icons tiny">delete</i>
                        </a>
                    </div>
                </div>
            `;
            
            $backupsList.append(backupHtml);
        });
        
        // Add click event for restore button
        $('.restore-backup-btn').on('click', function() {
            const backupId = $(this).data('id');
            if (confirm('Are you sure you want to restore this backup? All current tasks will be replaced with the tasks from this backup.')) {
                restoreBackup(backupId);
            }
        });
        
        // Add click event for delete button
        $('.delete-backup-btn').on('click', function() {
            const backupId = $(this).data('id');
            if (confirm('Are you sure you want to delete this backup? This action cannot be undone.')) {
                deleteBackup(backupId);
            }
        });
    }
    
    // Create new backup
    function createBackup() {
        $.ajax({
            url: '{{ url_for('.create_backup') }}',
            type: 'POST',
            success: function(data) {
                M.toast({html: data.message});
                
                // If there's a warning message (e.g. max backups reached), show it
                if (data.warning) {
                    M.toast({html: data.warning, classes: 'orange'});
                }
                
                // Reload backup list
                loadBackups();
            },
            error: function(xhr) {
                console.error('Error creating backup:', xhr);
                M.toast({html: 'Failed to create backup', classes: 'red'});
            }
        });
    }
    
    // Restore backup
    function restoreBackup(backupId) {
        $.ajax({
            url: `{{ url_for('.restore_backup', backup_id=0) }}`.replace('0', backupId),
            type: 'POST',
            success: function(data) {
                M.toast({html: data.message});
                
                // Refresh page to show restored tasks
                location.reload();
            },
            error: function(xhr) {
                console.error('Error restoring backup:', xhr);
                M.toast({html: 'Failed to restore backup', classes: 'red'});
            }
        });
    }
    
    // Delete backup
    function deleteBackup(backupId) {
        $.ajax({
            url: `{{ url_for('.delete_backup', backup_id=0) }}`.replace('0', backupId),
            type: 'DELETE',
            success: function(data) {
                M.toast({html: data.message});
                
                // Reload backup list
                loadBackups();
            },
            error: function(xhr) {
                console.error('Error deleting backup:', xhr);
                M.toast({html: 'Failed to delete backup', classes: 'red'});
            }
        });
    }
    
    // Backup icon click event
    $('#backup-toggle').on('click', function(e) {
        e.stopPropagation();
        $('#backup-content').toggleClass('hide');
        
        // If backup panel is shown, load backup list
        if (!$('#backup-content').hasClass('hide')) {
            loadBackups();
        }
    });
    
    // Close button click event
    $('.backup-close').on('click', function(e) {
        e.stopPropagation();
        $('#backup-content').addClass('hide');
    });
    
    // Create backup button click event
    $('#create-backup-btn').on('click', function() {
        createBackup();
    });
    
    // Prevent click events from bubbling inside backup panel
    $('#backup-content').on('click', function(e) {
        e.stopPropagation();
    });
    
    // Click outside to close backup panel
    $(document).on('click', function(e) {
        if (!$(e.target).closest('#backup-panel').length) {
            $('#backup-content').addClass('hide');
        }
    });
    
    // ==== Global Search & Replace Functionality ==== //
    
    // Store search results
    let searchResults = [];
    
    // Execute global search
    function searchTasks(searchText) {
        if (!searchText) {
            $('#search-results').html('<div class="no-results center-align"><p>{{ _('Please enter search text') }}</p></div>');
            $('#search-count').text('0');
            $('#replace-btn').prop('disabled', true);
            return;
        }
        
        // Reset search results
        searchResults = [];
        
        // Get all tasks
        const $items = $('.item');
        
        if ($items.length === 0) {
            $('#search-results').html('<div class="no-results center-align"><p>No tasks found</p></div>');
            $('#search-count').text('0');
            $('#replace-btn').prop('disabled', true);
            return;
        }
        
        // Find matching tasks
        $items.each(function() {
            const $item = $(this);
            const taskId = $item.data('id');
            // 获取任务文本的安全方法
            const $bodyElement = $item.find(`#body${$item.data('id')}`);
            let taskText = '';
            
            // 如果找到了元素，获取其文本内容
            if ($bodyElement.length) {
                // 获取纯文本内容，排除分类标签和截止日期
                const fullText = $bodyElement.text().trim();
                
                // 移除可能存在的类别标签和截止日期文本
                const categoryText = $bodyElement.find('.category-badge').text().trim();
                const deadlineText = $bodyElement.find('.deadline-text').text().trim();
                
                // 从完整文本中删除类别和截止日期文本
                taskText = fullText.replace(categoryText, '').replace(deadlineText, '').trim();
            } else {
                // 尝试从data-body属性获取
                taskText = String($item.data('body') || '');
            }
            
            const taskCategory = $item.data('category');
            
            // 确保taskText是字符串并且执行搜索
            if (taskText && typeof taskText === 'string' && taskText.indexOf(searchText) !== -1) {
                // 添加到搜索结果列表
                searchResults.push({
                    id: taskId,
                    text: taskText,
                    category: taskCategory,
                    element: $item
                });
            }
        });
        
        // Update result count
        $('#search-count').text(searchResults.length);
        
        // If no search results
        if (searchResults.length === 0) {
            $('#search-results').html('<div class="no-results center-align"><p>No matches found</p></div>');
            $('#replace-btn').prop('disabled', true);
            return;
        }
        
        // Enable replace button
        $('#replace-btn').prop('disabled', false);
        
        // Render search results
        renderSearchResults(searchText);
    }
    
    // Render search results
    function renderSearchResults(searchText) {
        const $searchResults = $('#search-results');
        
        // Clear results list
        $searchResults.empty();
        
        // Add each search result item
        searchResults.forEach(result => {
            // Highlight matching text
            const highlightedText = result.text.replace(
                new RegExp(searchText, 'g'), 
                `<span class="search-result-match">${searchText}</span>`
            );
            
            const resultHtml = `
                <div class="search-result-item" data-id="${result.id}">
                    <div class="search-result-info">
                        <span class="search-result-category" style="background-color: ${categoryColors[result.category] || '#9E9E9E'}">${result.category}</span>
                    </div>
                    <div class="search-result-text">${highlightedText}</div>
                </div>
            `;
            
            $searchResults.append(resultHtml);
        });
        
        // Add click event for search result items to scroll to task
        $('.search-result-item').on('click', function() {
            const taskId = $(this).data('id');
            const $task = $(`.item[data-id="${taskId}"]`);
            
            if ($task.length) {
                // Ensure task is visible (might be hidden by filters)
                $('#all-item').parent().addClass('active').siblings().removeClass('active');
                $('.category-filter.all').addClass('active').siblings().removeClass('active');
                applyAllFilters();
                
                // Scroll to task position and highlight
                $('html, body').animate({
                    scrollTop: $task.offset().top - 100
                }, 500);
                
                $task.addClass('highlight-task');
                setTimeout(() => {
                    $task.removeClass('highlight-task');
                }, 2000);
            }
        });
    }
    
    // Execute global replacement
    function replaceText(searchText, replaceText) {
        if (!searchText || searchResults.length === 0) {
            return;
        }
        
        // Loop through all search results, execute replacement
        searchResults.forEach(result => {
            // Get task element
            const $taskElement = result.element;
            
            // Get original task text
            let originalText = result.text;
            
            // Execute replacement
            const newText = originalText.replace(new RegExp(searchText, 'g'), replaceText);
            
            // Update task text
            const $bodyElement = $taskElement.find(`#body${result.id}`);
            // Keep category badge and deadline, only update text content
            const $categoryBadge = $bodyElement.find('.category-badge').clone();
            const $deadlineText = $bodyElement.find('.deadline-text').clone();
            
            // Clear content and re-add
            $bodyElement.empty();
            $bodyElement.append($categoryBadge);
            $bodyElement.append(' ' + newText + ' '); // Add spaces to ensure correct format
            if ($deadlineText.length) {
                $bodyElement.append($deadlineText);
            }
            
            // Update data-body attribute for future searches
            $taskElement.data('body', newText);
            
            // Update task object data
            result.text = newText;
            
            // Get task ID
            const taskId = result.id;
            
            // Get current task completion status
            const isDone = $taskElement.data('done');
            
            // Save changes to database - use existing edit API
            $.ajax({
                type: 'PUT',
                url: `{{ url_for('.edit_item', item_id=0) }}`.replace('0', taskId),
                contentType: 'application/json',
                data: JSON.stringify({
                    body: newText,
                    done: isDone
                }),
                success: function(data) {
                    // Replacement successful
                    console.log('Task updated:', taskId);
                },
                error: function(xhr) {
                    // Replacement failed
                    console.error('Error updating task:', xhr);
                    M.toast({html: 'Failed to update task', classes: 'red'});
                }
            });
        });
        
        // Show success message
        M.toast({html: `Replaced ${searchResults.length} occurrence(s)`});
        
        // Clear search results
        searchResults = [];
        $('#search-results').html('<div class="no-results center-align"><p>{{ _('Replacement complete') }}</p></div>');
        $('#search-count').text('0');
        $('#replace-btn').prop('disabled', true);
    }
    
    // Search button click event
    $('#search-btn').on('click', function() {
        const searchText = $('#search-text').val().trim();
        searchTasks(searchText);
    });
    
    // Replace button click event
    $('#replace-btn').on('click', function() {
        const searchText = $('#search-text').val().trim();
        const replacementText = $('#replace-text').val();
        
        // Confirm replacement
        if (confirm(`Are you sure you want to replace "${searchText}" with "${replacementText}"? This will affect ${searchResults.length} occurrence(s).`)) {
            replaceText(searchText, replacementText);
        }
    });
    
    // Search box enter key event
    $('#search-text').on('keypress', function(e) {
        if (e.which === 13) { // Enter key
            const searchText = $(this).val().trim();
            searchTasks(searchText);
        }
    });
    
    // Search & replace button click event
    $('#search-replace-toggle-btn').on('click', function(e) {
        e.stopPropagation();
        $('#search-replace-content').toggleClass('hide');
    });
    
    // Close button click event
    $('.search-replace-close').on('click', function(e) {
        e.stopPropagation();
        $('#search-replace-content').addClass('hide');
        $('#search-replace-toggle-btn').css('transform', '');
    });
    
    // Prevent click events from bubbling inside search panel
    $('#search-replace-content').on('click', function(e) {
        e.stopPropagation();
    });
    
    // Click outside to close search panel
    $(document).on('click', function(e) {
        if (!$(e.target).closest('#search-replace-panel').length) {
            $('#search-replace-content').addClass('hide');
            $('#search-replace-toggle-btn').css('transform', '');
        }
    });
});
</script>
{% endblock %}
